<?php

namespace App\Console\Commands\System\NSQ;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;

class CreateTopic extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'system:nsq:create_topic';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'NSQ创建topic命令';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $connectionName = $this->choice('选择你要创建的NSQ连接名', array_keys(config('nsq')), 0);
        $topicName      = $this->ask('请输入你要创建的topic名字，例如： kfos.order.merchantOrder.fullPaid');
        $url            = config("nsq.{$connectionName}.address");
        // 查询topic是否存在
        $topics = (array)Http::withOptions(['http_errors' => false])
            ->get(rtrim($url, '/') . '/topics')
            ->json('topics');
        if (in_array($topicName, $topics)) {
            $this->error("当前topic已存在");
            return 1;
        }
        $nsqdUrl = str_replace(':4161', ':4151', $url);
        $res     = Http::withOptions(['http_errors' => false])
            ->post(rtrim($nsqdUrl, '/') . '/topic/create?topic=' . $topicName);
        $status  = $res->status();
        if (200 === $status) {
            $this->info("创建成功");
            return 0;
        }
        $this->error("创建失败，NSQD返回状态：{$status}");
        return $status;
    }
}
